<template>
    <div class="app-container">
        <!-- <PageHeader :border="false" title="设备管理" />
        <el-divider class="mt-0" /> -->

        <el-row class="mb-3" :gutter="20">
            <el-col :span="4">
                <el-card style="height: calc(95vh - 135px)">
                    <div class="head-container">
                        <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search"
                            style="margin-bottom: 20px" />
                    </div>
                    <div class="head-container" style="height: calc(100vh - (85px + 40px + 30px));overflow-y: auto">
                        <el-tree :data="deptOptions"
                            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                            :expand-on-click-node="false" :filter-node-method="filterNode"
                            :default-expanded-keys="defaultexpandedkeys"
                            ref="deptTreeRef" node-key="deptId" highlight-current @node-click="handleNodeClick" />
                    </div>
                </el-card>
            </el-col>
            <el-col :span="10">
                <el-card style="height: calc(95vh - 135px)">
                    <div class="head-container">
                        <!-- <el-input v-model="roomType" placeholder="请输入" clearable prefix-icon="Search"
                            style="margin-bottom: 20px" /> -->
                    </div>
                    <div class="head-container">
                        <el-tree :data="roomTypeOptions" :render-content="renderContent" :expand-on-click-node="true"
                            :default-expand-all="false" ref="roomTypeTreeRef" node-key="id" highlight-current
                            @node-click="roomTypeClick" />
                    </div>
                    <!-- :props="{ value: 'id', label: 'label', children: 'children' }" -->
                </el-card>
            </el-col>
            <el-col :span="10">
                <div class="head-container">
                    <el-space class="mb-3">
                        <el-button type="primary" plain icon="Plus" @click="SaveClick">
                            保存
                        </el-button>
                    </el-space>
                </div>
                <el-card style="height: calc(90vh - 135px)">
                    <div class="head-container">
                        <el-tree :data="ChannelOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
                            :expand-on-click-node="true" :default-expand-all="true" :show-checkbox="true"
                            ref="ChannelTreeRef" node-key="id" highlight-current
                            :default-checked-keys="defaultCheckedData" @check="ChannelCheck" />
                    </div>
                    <!-- :render-content="ChannelContent" -->
                </el-card>
            </el-col>
        </el-row>
        <!-- <AddEditDevice ref="AddEditDeviceRef" @getDeviceList="getDeviceLists" /> -->

    </div>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { getCurrentInstance } from "vue";
import { toRaw } from "vue";
import PageHeader from "@/components/PageHeader/index.vue";



import { listDept, } from "@/api/system/dept";
import { getUserProfile } from "@/api/system/user";
import { getroomTypeTree, getdeviceChannelTree, createApplication, getApplicationList } from "@/api/ParameterSetting/Device";


const { proxy } = getCurrentInstance();
const { sys_normal_disable, nj_device_type, nj_monitor_quantity } = proxy.useDict('sys_normal_disable', 'nj_device_type', 'nj_monitor_quantity')


const queryParamsRef = ref()
// const DeviceTableRef = ref()
const defaultexpandedkeys = ref([])

const deleteStatus = ref(true)
// const AddEditDeviceRef = ref({})

const unitId = ref()
const deptList = ref([])

const treeloading = ref(true);
const isExpandAll = ref(true);

const loading = ref(false)

const total = ref(0)

const monitorapplication = ref({
    roomId: '',
    objectId: '',
    type: "1",
    viewChannels: undefined
})

const queryParams = ref({})
const paging = ref({
    pageNum: 1,// 页码    
    pageSize: 10// 分页数量
})



onMounted(() => {
    getDeptTree();
})

const deptName = ref("");
const deptOptions = ref(undefined);
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
    if (!value) return true;
    return data.deptName.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
    proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询部门下拉树结构 */
function getDeptTree() {
    listDept().then(response => {
        deptOptions.value = response.data.filter(
            item => item.isUnit === true
        );
        deptOptions.value = proxy.handleTree(deptOptions.value, "deptId");
        defaultexpandedkeys.value = []
        defaultexpandedkeys.value = deptOptions.value.map(item => item.deptId);
    });
};
/** 节点单击事件 */
function handleNodeClick(data) {
    roomTypeParams.value.unitId = data.deptId;
    getroomTypeTrees()
    getdeviceChannelTrees('0')//置空
};


const roomType = ref("");
const roomTypeOptions = ref(undefined);
const roomTypeParams = ref(
    {
        unitId: '0'
    }
)

/** 查询房间类型下拉树结构 */
function getroomTypeTrees() {
    getroomTypeTree(roomTypeParams.value).then(response => {
        roomTypeOptions.value = response.data
    });
};
/** 自定义节点 */
function renderContent(h, { node, data, store }) {
    if (node.label != undefined) {
        if (node.data.type === "1") {
            return "<房>" + node.label
        }
        else {
            return "<监>" + node.label
        }
    }
    else {
        return node.data.roomname
    }
}
/** 节点单击事件 */
function roomTypeClick(data, node) {
    if (data.roomId !== undefined) {
        monitorapplication.value = {
            roomId: '',
            objectId: '',
            type: "1",
        };
        monitorapplication.value.roomId = data.roomId
        monitorapplication.value.objectId = node.parent.data.id

        queryParams.value.roomId = data.roomId
        queryParams.value.objectId = node.parent.data.id
    } else {
        monitorapplication.value = {
            objectId: '',
            type: "1",
        };
        monitorapplication.value.objectId = data.id
        queryParams.value.objectId = data.id;
    }

    getdeviceChannelTrees(roomTypeParams.value.unitId)

};

const ChannelOptions = ref(undefined);
const ChannelData = ref([])
const Channelchildren = ref([])
/** 查询通道下拉树结构 */
function getdeviceChannelTrees(data) {
    getdeviceChannelTree(data).then(response => {
        ChannelData.value = [];
        for (var i = 0; i < response.data.length; i++) {
            // console.log(response.data[i].monitorChannels.length)
            Channelchildren.value = []
            for (var j = 0; j < response.data[i].monitorChannels.length; j++) {
                const newchannelsId = {
                    id: response.data[i].monitorChannels[j].monitorchannelsId,
                    label: response.data[i].monitorChannels[j].channelname,
                    channelcode: response.data[i].monitorChannels[j].channelcode,
                    channelname: response.data[i].monitorChannels[j].channelname,
                    channels: response.data[i].monitorChannels[j].channels,
                    imglevel: response.data[i].monitorChannels[j].imglevel,
                    iswoman: response.data[i].monitorChannels[j].iswoman,
                    monitorchannelsId: response.data[i].monitorChannels[j].monitorchannelsId,
                    monitorserverId: response.data[i].monitorChannels[j].monitorserverId,
                    state: response.data[i].monitorChannels[j].state
                };
                Channelchildren.value.push(newchannelsId);
            }
            // console.log(Channelchildren)
            const newChild = {
                id: response.data[i].monitorserverId,
                label: response.data[i].servername,
                monitorserverId: response.data[i].monitorserverId,
                servername: response.data[i].servername,
                servercode: response.data[i].servercode,
                serverip: response.data[i].serverip,
                children: Channelchildren.value
            };
            ChannelData.value.push(newChild);
        }
        ChannelOptions.value = ChannelData
        // console.log(ChannelOptions)
    });

    if (data != "0") {
        getApplicationLists();
    }
};
const Channelnode = ref([])
const nodes = ref([])
// /** 自定义通道节点 */
// function ChannelContent(h, { node, data, store }) {
//     if (node.data.servername != undefined) {
//         return node.data.servername
//     }
//     else {
//         const newChild = {
//             id: node.id,
//             monitorchannelsId: node.data.monitorchannelsId
//         };
//         Channelnode.value.push(newChild);
//         return node.data.channelname
//     }
// }

const defaultCheckedData = ref([])
const Options = ref([]);
// 已选择通道
const getApplicationLists = async () => {
    let channelsId = [];
    await getApplicationList(queryParams.value, paging.value).then(res => {
        res.rows.forEach(res => {
            console.log(res.monitorChannelsId)
            // channelsId = channelsId.concat(res.monitorchannelsId);
            channelsId.push(res.monitorChannelsId);
        });
        console.log(channelsId)
    })
    monitorapplication.value.viewChannels = channelsId
    defaultCheckedData.value = channelsId
}

/** 通道选择 */
function ChannelCheck(data, node) {
    console.log(node)
    let channelsId = [];
    node.checkedNodes.forEach(node => {
        if (node.monitorchannelsId !== undefined) {
            channelsId = channelsId.concat(node.monitorchannelsId);
        }
    });
    console.log(channelsId)
    monitorapplication.value.viewChannels = channelsId
};

/** 保存 */
function SaveClick() {
    console.log(monitorapplication.value.viewChannels.length)
    if (monitorapplication.value.viewChannels.length === 0) {
        // alert("请选择通道");
        proxy.$modal.msgError(`请选择通道`)
    }
    else {
        createApplication(monitorapplication.value).then(res => {
            proxy.$modal.msgSuccess("保存成功");
            // changeShowStatus()
            // emit('getPassageList', '来了老弟')
        })
    }

};

</script>

<style lang="scss" scoped></style>